import * as ysApi from "@/apis/g.ys";
import { getCachedValue } from "@/utils/local-storage-cache";
import { Subject, distinctUntilChanged, filter } from "rxjs";
import { computed, defineComponent, onMounted, onUnmounted, ref, watch } from "vue";
import { useYsStore } from "./store";

import styles from "./CharactersCarousel.module.scss";

import emblaCarouselVue from "embla-carousel-vue";

import AvatarCard from "./AvatarCard";

type ExtValueUrl = { name: string; url: string };
type ExtValue = string | ExtValueUrl[];
type Ext = { [code: string]: ExtValue };

type YsCharacter = {
  name: string;
  infoId: number;
  avatarUrl: string;
  lihuiUrl: string;
  namePicUrl: string;
  elementIconUrl: string;
  descHtml: string;
  quotePicUrl: string;
};
/**
 * 732_0  头像
 * 732_1  pc立绘
 * 732_15 移动端立绘
 * 732_2  名字图
 * 732_3  元素图标
 * 732_7  一段 html 介绍
 * 732_8  图片语录
 */

function itemToCharacter(it: DYsContentItem): YsCharacter {
  const ext: Ext = JSON.parse(it.sExt);
  return {
    name: it.sTitle,
    infoId: it.iInfoId,
    avatarUrl: (ext["732_0"] as ExtValueUrl[])[0].url,
    lihuiUrl: (ext["732_1"] as ExtValueUrl[])[0].url,
    namePicUrl: (ext["732_2"] as ExtValueUrl[])[0].url,
    elementIconUrl: (ext["732_3"] as ExtValueUrl[])[0].url,
    descHtml: ext["732_7"] as string,
    quotePicUrl: (ext["732_8"] as ExtValueUrl[])[0].url,
  };
}

const CharactersCarousel = defineComponent({
  setup() {
    const ysStore = useYsStore();
    const cid = computed(() => ysStore.activeNation?.chanId);
    const characters = ref<YsCharacter[]>([]);
    const [emblaRef, emblaApi] = emblaCarouselVue({ align: "start" });

    const loadCharacters = async (chanId: string) => {
      try {
        const cacheKey = `__ys_nation_${chanId}_characters__`;
        const pager = await getCachedValue(cacheKey, 3600 * 24 * 7, () => ysApi.getByChanId({ chanId }));
        console.log("pager", pager);
        characters.value = pager.list.map(itemToCharacter);
      } catch (err) {
        console.error(`Error occurs when getting ys characters in nation ${chanId}:`, err);
      }
    };

    const cidSubject = new Subject<string>();
    const cidSubscription = cidSubject
      .pipe(filter((it) => !!it))
      .pipe(distinctUntilChanged())
      .subscribe((chanId) => {
        console.log("load on change ", chanId);
        loadCharacters(chanId);
      });

    const prev = () => {
      emblaApi.value?.scrollPrev();
    };
    const next = () => {
      emblaApi.value?.scrollNext();
    };

    watch(cid, (newCid) => {
      cidSubject.next(newCid);
    });

    onMounted(() => {
      cidSubject.next(cid.value);
    });

    onUnmounted(() => {
      cidSubscription.unsubscribe();
    });

    return () => (
      <div class={styles["carousel-container"]}>
        {/* biome-ignore lint/a11y/useKeyWithClickEvents: <explanation> */}
        <div class={styles.left} onClick={prev} />
        <div class={styles.embla__viewport} ref={emblaRef}>
          <div class={styles.embla__container}>
            {characters.value.map((it) => (
              <div key={it.infoId} class={styles.embla__slide}>
                <AvatarCard url={it.avatarUrl} name={it.name} />
              </div>
            ))}
          </div>
        </div>
        {/* biome-ignore lint/a11y/useKeyWithClickEvents: <explanation> */}
        <div class={styles.right} onClick={next} />
      </div>
    );
  },
});

export default CharactersCarousel;
